//
//  PayDetailViewController.m
//  DaDaLiCai
//
//  Created by User on 15/11/23.
//  Copyright © 2015年 Mikeshihua. All rights reserved.
//
#import "SuccessViewController.h"
#import "LoginViewController.h"
#import "PayDetailViewController.h"
#import "ProductDetailCell.h"
#import <AlipaySDK/AlipaySDK.h>
#import "Order.h"
#import "DataSigner.h"

@interface PayDetailViewController ()<UITableViewDelegate, UITableViewDataSource,UITextFieldDelegate>

@property (nonatomic, strong) ProductModel *model;

@property (nonatomic, strong) UITableView *listTableView;

@property (nonatomic, strong) UIButton *sureBt;

@property (nonatomic, strong) UITextField *moneyTextField;

@property (nonatomic, strong) UITextField *numberTextField;

@property (nonatomic, assign) BOOL          isAffirm;

@property (nonatomic, assign) float         keyboardHeight;

@property (nonatomic, assign) CGSize       lastSize;

@end

@implementation PayDetailViewController

- (id)initWithModel:(ProductModel *)model
{
    self = [super init];
    
    if(self)
    {
        _model = model;
    }
    return self;
}

//创建导航栏
-(void)createTheNavigationBar
{
    TopView *topView = [[TopView alloc] initWithFrame:CGRectMake(0.0f, 0.0f, SCREEN_HEIGHT, 64.0f)];
    topView.backgroundColor = [UIColor hexStringToColor:COLOR_VALUE];
    [topView setTitile:@"支付详情"];
    [self.view addSubview:topView];
    
    UIButton * backBtn = [[UIButton alloc]initWithFrame:CGRectMake(10.0f, 35.0f, 49.0f, 16.0f)];
    [backBtn setImage:[UIImage imageNamed:@"icon_back"] forState:UIControlStateNormal];
    [backBtn addTarget:self action:@selector(buttonBackTapped:) forControlEvents:UIControlEventTouchUpInside];
    backBtn.titleLabel.textAlignment = NSTextAlignmentRight;
    [topView addSubview:backBtn];
}

- (UIButton *)sureBt
{
    if(!_sureBt)
    {
        _sureBt = [[UIButton alloc]initWithFrame:CGRectMake(0.0f, SCREEN_HEIGHT - 50.0f, SCREEN_WIDTH, 50.0f)];
        [_sureBt setBackgroundColor:[UIColor hexStringToColor:kColorBtnEnabled] forState:UIControlStateNormal];
        _sureBt.enabled = FALSE;
        [_sureBt setTitle:@"确认购买" forState:UIControlStateNormal];
        [_sureBt addTarget:self action:@selector(buttonSureTapped:) forControlEvents:UIControlEventTouchUpInside];
        [_sureBt setTitleColor:[UIColor whiteColor] forState:UIControlStateNormal];
    }
    return _sureBt;
}

//确认购买按钮

- (void)buttonSureTapped:(id)sender
{
    //投资金额和理财经理工号
    if ([AccountTools getUserToken])
    {
        if (_moneyTextField.text.length <= 0)
        {
            ALERT_VIEW(@"请输入投资金额");
            return;
        }
        if (![self validateMoney:_moneyTextField.text])
        {
            ALERT_VIEW(@"请输入合法的金额");
            return;
        }
        if (_numberTextField.text.length <=0)
        {
            ALERT_VIEW(@"请输入理财经理工号");
            return;
        }
        if (_numberTextField.text.length <8 || _numberTextField.text.length > 10)
        {
            ALERT_VIEW(@"请输入正确的理财经理工号");
            return;
        }
        if (!_isAffirm) {
            ALERT_VIEW(@"请选择支付宝支付");
            return;
        }
        
        [self chargeTheMoney:_model];
        
    }
    else
    {
        //登录
        LoginViewController * vc = [[LoginViewController alloc]init];
        [self presentViewController:vc animated:TRUE completion:^{
        }];
    }
}

- (UITableView *)listTableView
{
    if(!_listTableView)
    {
        _listTableView = [[UITableView alloc]initWithFrame:CGRectMake(0.0f, 64.0f, SCREEN_WIDTH, SCREEN_HEIGHT - 114.0f)];
        _listTableView.backgroundColor = [UIColor hexStringToColor:kColorBackground];
        _listTableView.dataSource = self;
        _listTableView.delegate = self;
        _listTableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _listTableView.tableFooterView = [[UIView alloc]initWithFrame:CGRectZero];
        
        UITapGestureRecognizer * gesture = [[UITapGestureRecognizer alloc]initWithTarget:self action:@selector(keyboardDown)];
        [_listTableView addGestureRecognizer:gesture];
    }
    return _listTableView;
}

#pragma mark-----------dataSource和delegate
-(NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    if(section == 0)
        return 4;
    else
        return 1;
}

- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView
{
    return 4;
}

- (UIView *)tableView:(UITableView *)tableView viewForHeaderInSection:(NSInteger)section
{
    
    UIView *headView = [[UIView alloc]initWithFrame:CGRectMake(0.0f, 0.0f, SCREEN_WIDTH, 35.0f)];
    headView.backgroundColor = [UIColor hexStringToColor:kColorBackground];
    
    UILabel *headLab = [[UILabel alloc]initWithFrame:CGRectMake(15.0f, 0.0f, SCREEN_WIDTH - 15.0f, 35.0f)];
    headLab.backgroundColor = [UIColor clearColor];
    headLab.textColor = [UIColor hexStringToColor:@"#969494"];
    headLab.font = [UIFont systemFontOfSize:13.0f];
    
    if(section == 0)
        headLab.text = @"确认产品信息";
    if(section == 1)
        headLab.text = @"输入投资金额";
    if(section == 2)
        headLab.text = @"输入理财经理工号";
    if (section == 3) {
        headLab.text = @"支付宝支付";
    }
    [headView addSubview:headLab];
    return headView;
}

- (CGFloat)tableView:(UITableView *)tableView heightForHeaderInSection:(NSInteger)section
{
    return 35.0f;
}


-(UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    ProductDetailCell *cell = [[ProductDetailCell alloc]initWithStyle:UITableViewCellStyleValue1 reuseIdentifier:@"cell"];
    if(indexPath.section == 0)
    {
        if(indexPath.row == 0)
            cell.textLabel.text = _model.pname;
        cell.textLabel.numberOfLines = 0;
        if(indexPath.row == 1)
        {
            cell.textLabel.text = @"编码";
            cell.detailTextLabel.text = _model.pcode;
        }
        if(indexPath.row == 2)
        {
            cell.textLabel.text = @"产品期限";
            cell.detailTextLabel.text = [NSString stringWithFormat:@"%@天",_model.revperiod];
        }
        if(indexPath.row == 3)
        {
            cell.textLabel.text = @"预期收益";
            
            float revate = ([_model.revrate intValue])/10.0;
            cell.detailTextLabel.text = [NSString stringWithFormat:@"%.2f%%",revate];
        }
        
        return cell;
    }
    
    if(indexPath.section == 1)
    {
        cell.textLabel.text = @"投资金额";
        cell.textLabel.textColor = [UIColor hexStringToColor:@"#5A5A5A"];
        _moneyTextField = [[UITextField alloc]initWithFrame:CGRectMake(SCREEN_WIDTH - 156, 0.0f, 140, 50.0f)];
        _moneyTextField.textAlignment = NSTextAlignmentRight;
        _moneyTextField.textColor = [UIColor hexStringToColor:COLOR_VALUE];
        _moneyTextField.keyboardType = UIKeyboardTypeDecimalPad;
        _moneyTextField.font = [UIFont systemFontOfSize:15.0f];
        _moneyTextField.placeholder = @"请输入投资金额";
        _moneyTextField.delegate = self;
        [_moneyTextField addTarget:self action:@selector(isTheSureBtnCanClick:) forControlEvents:UIControlEventEditingChanged];
        [cell.contentView addSubview:_moneyTextField];
        
        return cell;
    }
    
    if(indexPath.section == 2)
    {
        cell.textLabel.textColor = [UIColor hexStringToColor:@"#5A5A5A"];
        cell.textLabel.text = @"理财经理工号";
        
        _numberTextField = [[UITextField alloc]initWithFrame:CGRectMake(SCREEN_WIDTH - 156, 0.0f, 140, 50.0f)];
        _numberTextField.textAlignment = NSTextAlignmentRight;
        _numberTextField.textColor = [UIColor redColor];
        _numberTextField.keyboardType = UIKeyboardTypeNumberPad;
        _numberTextField.font = [UIFont systemFontOfSize:15.0f];
        _numberTextField.placeholder = @"请输入工号";
        _numberTextField.delegate = self;
        [_numberTextField addTarget:self action:@selector(isTheSureBtnCanClick:) forControlEvents:UIControlEventEditingChanged];

        [cell.contentView addSubview:_numberTextField];
        
        return cell;
    }
    if(indexPath.section == 3)
    {
        cell.textLabel.textColor = [UIColor hexStringToColor:@"#5A5A5A"];
        cell.textLabel.text = @"支付宝支付";
        cell.imageView.image = [UIImage imageNamed:@"icon_alipay"];
     
        UIButton * btn = [[UIButton alloc]initWithFrame:CGRectMake(SCREEN_WIDTH - 25 - 16, (50 - 25)/2.0, 25, 25)];
        [btn setImage:[UIImage imageNamed:@"icon_choose"] forState:UIControlStateNormal];
        [btn addTarget:self action:@selector(buttonChooseTapped:) forControlEvents:UIControlEventTouchUpInside];
        [cell addSubview:btn];
        
        return cell;
    }
    return nil;
}
-(void)keyboardDown
{
    [self.view endEditing:TRUE];
}
- (void)touchesBegan:(NSSet<UITouch *> *)touches withEvent:(UIEvent *)event
{
    [self.view endEditing:TRUE];
}

-(void)keyboardWillHide:(NSNotification *)note
{
    _listTableView.contentSize = _lastSize;
}
-(CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    if(indexPath.section == 0 && indexPath.row == 0)
    {
        if ([UILabel height:_model.pname widthOfFatherView:SCREEN_WIDTH - 15.0f textFont:[UIFont systemFontOfSize:16.0f]] <50)
        {
            return 50;
        }
        return [UILabel height:_model.pname widthOfFatherView:SCREEN_WIDTH - 15.0f textFont:[UIFont systemFontOfSize:16.0f]];
        
    }
    return 50.0f;
}
- (void)buttonBackTapped:(id)sender
{
    [[AnimationIndicator sharedIndicator]stopAnimationWithLoadText:@"" withType:TRUE];
    [self.navigationController popViewControllerAnimated:TRUE];
}

- (void)viewDidLoad {
    [super viewDidLoad];
    // Do any additional setup after loading the view.
    self.view.backgroundColor = [UIColor whiteColor];
    [self createTheNavigationBar];
    [self.view addSubview:self.listTableView];
    [self.view addSubview:self.sureBt];
    
}
-(void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    [[NSNotificationCenter defaultCenter]addObserver:self selector:@selector(keyboardWillHide:) name:UIKeyboardWillHideNotification  object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector (keyboardShow:)
                                                 name: UIKeyboardDidShowNotification object:nil];
    
    [[NSNotificationCenter defaultCenter] addObserver:self selector:@selector(reloginView) name:@"reLogin" object:nil];
    
}
-(void)viewWillDisappear:(BOOL)animated
{
    [super viewWillDisappear:animated];
    [[NSNotificationCenter defaultCenter]removeObserver:self];
}
//测试充值
-(void)chargeTheMoney:(id)sender
{
    ProductModel * model = (ProductModel *)sender;
    NSString * token = [[NSUserDefaults standardUserDefaults]objectForKey:@"token"];
    
    [[AnimationIndicator sharedIndicator]startAnimation];

    [AppGlobalClass PostDataWithNSstring:GETPAYDATA withDictionary:@{@"token":token,@"money":_moneyTextField.text,@"productId":model.pid,@"pyid":model.pyid,@"jobNumber":_numberTextField.text} success:^(NSDictionary *dictionary) {
        if([[dictionary objectForKey:@"success"] isEqualToNumber:[NSNumber numberWithBool:TRUE]])
        {
            //获取支付宝所需信息
            NSDictionary * mdict = [[[[dictionary objectForKey:@"responseData"]firstObject]objectForKey:@"rows"] firstObject];
            //生成订单信息及签名
            Order *order = [[Order alloc] init];
            
            order.partner = [mdict objectForKey:@"partner"];
            order.notifyURL = [mdict objectForKey:@"notifyUrl"];//回调
            order.itBPay = @"30m";
            order.showUrl = @"m.alipay.com";
            order.inputCharset = @"utf-8";
            order.paymentType = @"1";
            order.service = @"mobile.securitypay.pay";
            NSString * privateKey = [mdict objectForKey:@"privateKey"];//私钥
            order.seller = [mdict objectForKey:@"seller"];
            order.tradeNO = [mdict objectForKey:@"flowNo"];//订单号
            order.productName = [mdict objectForKey:@"subject"];//标题
            order.amount = [mdict objectForKey:@"totalFee"];//钱
            //            order.productDescription = [mdict objectForKey:@"body"];//描述
            order.productDescription = @"chzong";
            
            NSString *appScheme = @"DaDaLiCai";
            //将商品信息拼接成字符串
            NSString *orderSpec = [order description];
            
            //获取私钥并将商户信息签名,外部商户可以根据情况存放私钥和签名,只需要遵循RSA签名规范,并将签名字符串base64编码和UrlEncode
            id<DataSigner> signer = CreateRSADataSigner(privateKey);
            NSString *signedString = [signer signString:orderSpec];
            
            //将签名成功字符串格式化为订单字符串,请严格按照该格式
            NSString *orderString = nil;
            if (signedString != nil) {
                orderString = [NSString stringWithFormat:@"%@&sign=\"%@\"&sign_type=\"%@\"",
                               orderSpec, signedString, @"RSA"];
                
                
                [[AlipaySDK defaultService] payOrder:orderString fromScheme:appScheme callback:^(NSDictionary *resultDic) {
                    int reslutStatus = [[resultDic objectForKey:@"resultStatus"] intValue];
                    
                    switch (reslutStatus) {
                        case 9000:
                        {
                            SuccessViewController * vc = [[SuccessViewController alloc]initWithTitle:@"投资成功" andTips:@"恭喜您，投资已成功。"];
                            [self.navigationController pushViewController:vc animated:TRUE];
                        }
                            break;
                        case 8000:
                        {
                            ALERT_VIEW(@"正在处理中");
                        }
                            break;
                        case 4000:
                        {
                            ALERT_VIEW(@"订单支付失败");
                        }
                            break;
                        case 6001:
                        {
                            ALERT_VIEW(@"用户中途取消");
                        }
                            break;
                        case 6002:
                        {
                            ALERT_VIEW(@"网络连接错误");
                        }
                            break;
                        default:
                            break;
                    }
                }];
            }
        }
        else
        {
            ALERT_VIEW([dictionary objectForKey:@"message"]);
        }
        [[AnimationIndicator sharedIndicator]stopAnimationWithLoadText:@"" withType:TRUE];

    } failure:^(NSError *error) {
        [[AnimationIndicator sharedIndicator]stopAnimationWithLoadText:@"" withType:TRUE];
    } networkerror:^(NSString *networkerror) {
        [[AnimationIndicator sharedIndicator]stopAnimationWithLoadText:@"" withType:TRUE];
    }];
    
}
-(void)buttonChooseTapped:(id)sender
{
    UIButton * btn = (UIButton *)sender;
    _isAffirm = !_isAffirm;
    if (_isAffirm)
    {
         [btn setImage:[UIImage imageNamed:@"icon_affirm"] forState:UIControlStateNormal];
    }else
    {
         [btn setImage:[UIImage imageNamed:@"icon_choose"] forState:UIControlStateNormal];
    }
    [self isTheSureBtnCanClick:nil];
}
- (void)didReceiveMemoryWarning {
    [super didReceiveMemoryWarning];
    // Dispose of any resources that can be recreated.
}
//金额验证
-(BOOL)validateMoney:(NSString *)money
{
    NSString *phoneRegex = @"^[0-9]+(\\.[0-9]{1,2})?$";
    NSPredicate *phoneTest = [NSPredicate predicateWithFormat:@"SELF MATCHES %@",phoneRegex];
    return [phoneTest evaluateWithObject:money];
}
-(void)reloginView
{
    UIAlertView *alert = [[UIAlertView alloc]initWithTitle:@"提示" message:@"账号在另一台机器登录，请重新登录!" delegate:self cancelButtonTitle:@"确定" otherButtonTitles:nil];
    [alert show];
}
#pragma mark alertDelegate

- (void)alertView:(UIAlertView *)alertView clickedButtonAtIndex:(NSInteger)buttonIndex
{
    [AccountTools exitLogin];
    
    LoginViewController *loginViewCon = [[LoginViewController alloc]init];
    [self presentViewController:loginViewCon animated:TRUE completion:^{}];
}
-(void)isTheSureBtnCanClick:(UITextField *)textField
{
    
    if (_numberTextField.text.length <=0 || _moneyTextField.text.length <=0 || !_isAffirm)
    {
        _sureBt.enabled = FALSE;
        [_sureBt setBackgroundColor:[UIColor hexStringToColor:kColorBtnEnabled] forState:UIControlStateNormal] ;
    }else
    {
        _sureBt.enabled = TRUE;
        [_sureBt setBackgroundColor:[UIColor hexStringToColor:COLOR_VALUE] forState:UIControlStateNormal] ;
    }
    if (textField == _moneyTextField)
    {
        NSString * string = _moneyTextField.text;
        NSInteger len = string.length;
        if ([string floatValue] > 100000)
        {
            _moneyTextField.text = [string substringToIndex:len-1];
        }
    }else
    {
        NSString * string = _numberTextField.text;
        if (string.length > 10)
        {
            _numberTextField.text = [string substringToIndex:10];
        }
    }
}
//键盘升起
- (void)keyboardShow:(NSNotification *)noti
{
    NSValue *value = [noti.userInfo objectForKey:UIKeyboardFrameEndUserInfoKey];
    CGRect keyboardFrame = [value CGRectValue];
    _lastSize = _listTableView.contentSize;
    _listTableView.contentSize = CGSizeMake(SCREEN_WIDTH, SCREEN_HEIGHT - 64 - 49 + keyboardFrame.size.height);
}
/*
#pragma mark - Navigation

// In a storyboard-based application, you will often want to do a little preparation before navigation
- (void)prepareForSegue:(UIStoryboardSegue *)segue sender:(id)sender {
    // Get the new view controller using [segue destinationViewController].
    // Pass the selected object to the new view controller.
}
*/

@end
